package servlet;

import java.io.*;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import util.*;
import bll.*;
import model.*;
import dal.*;

/**
 * Servlet implementation class CompanyServlet
 */
@WebServlet(urlPatterns = { "/QuotationItem", "/quotationItem", "/QuotationItemServlet", "/quotationItemServlet" }, initParams = { @WebInitParam(name = "mode", value = "") })
public class QuotationItemServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * Default constructor.
	 */
	public QuotationItemServlet() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html; charset=UTF-8");

		String mode = request.getParameter("mode");

		if (mode.equalsIgnoreCase("new")) {

			if (RightUtil.<QuotationItemModel> checkInsertRight()) {

				// TODO : MORE CODE HERE

				getServletContext().getRequestDispatcher("/quotationItemNew.jsp").forward(request, response);
			} else {
				// TODO no right
			}
		} else if (mode.equalsIgnoreCase("edit")) {

			QuotationItemModel query = new QuotationItemModel();
			String id = request.getParameter("id");
			query.setId(Integer.parseInt(id));

			GenericDal<QuotationItemModel, QuotationItemModelExt> dal = new GenericDal<QuotationItemModel, QuotationItemModelExt>(new QuotationItemModel());

			QuotationItemModel obj = null;
			try {
				obj = dal.select(query);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			if (obj != null) {

				// TODO : MORE CODE HERE

				request.setAttribute("quotation_item", obj);
				getServletContext().getRequestDispatcher("/quotationItemEdit.jsp").forward(request, response);

			} else {
				// TODO : data not found
			}
		} else if (mode.equalsIgnoreCase("view")) {

			QuotationItemModel query = new QuotationItemModel();
			String id = request.getParameter("id");
			query.setId(Integer.parseInt(id));

			GenericDal<QuotationItemModel, QuotationItemModelExt> dal = new GenericDal<QuotationItemModel, QuotationItemModelExt>(new QuotationItemModel());

			QuotationItemModel obj = null;
			try {
				obj = dal.select(query);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			if (obj != null) {
				// TODO : LOAD MASTER DATA HERE
				// It's specific code that cannot be generated

				request.setAttribute("quotation_item", obj);
				getServletContext().getRequestDispatcher("/quotationItemView.jsp").forward(request, response);

			} else {
				// TODO : data not found
			}
		} else if (mode.equalsIgnoreCase("quickInsert")) {
			QuotationItemModel obj = new QuotationItemModel();

			// TODO set name here

			GenericDal<QuotationItemModel, QuotationItemModelExt> dal = new GenericDal<QuotationItemModel, QuotationItemModelExt>(new QuotationItemModel());

			int res = 0;
			try {
				res = dal.insert(obj);
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			// TODO : return value
			if (res > 0)
			{
				
			}

		} else if (mode.equalsIgnoreCase("delete")) {

			QuotationItemModel query = new QuotationItemModel();
			String id = request.getParameter("id");
			query.setId(Integer.parseInt(id));

			GenericDal<QuotationItemModel, QuotationItemModelExt> dal = new GenericDal<QuotationItemModel, QuotationItemModelExt>(new QuotationItemModel());

			QuotationItemModel obj = null;
			try {
				obj = dal.select(query);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			String urlQuotation = "quotation.jsp";
			if(obj != null)
				urlQuotation += "?id=" + obj.getIdQuotationToString();
			
			int res = Integer.MIN_VALUE;
			try {
				res = dal.delete(query);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			if (res == 0) {
				// TODO success
				response.sendRedirect(urlQuotation);
				//getServletContext().getRequestDispatcher(urlQuotation).forward(request,	response);
			} else {
				// TODO fail
				getServletContext().getRequestDispatcher(urlQuotation).forward(request,	response);
			}
		} else if (mode.equalsIgnoreCase("getCascadeDropdowList")){
			response.setContentType("text/xml; charset=UTF-8");
			String idQuotation=request.getParameter("idParent");
			try{
			List<QuotationItemModel> list = CacheUtil.getQuotationItemList(Integer.parseInt(idQuotation));
			List<String> listQuotationItem = new ArrayList<String>();
			List<String> listQuotationItemId = new ArrayList<String>();
			for(int i=0;i<list.size();i++)
			{
				listQuotationItem.add(i, list.get(i).getName());
				listQuotationItemId.add(i, list.get(i).getIdToString());
			}
			PrintWriter out = response.getWriter();
			
			String resultXML = CommonUtil.createAjaxResultXML("quotation_item", listQuotationItem, listQuotationItemId);
			out.println(resultXML);
			}
			catch(Exception e)
			{}
			
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html; charset=UTF-8");

		String mode = request.getParameter("mode");

		if (mode.equalsIgnoreCase("insert")) {

			QuotationItemModel obj = new QuotationItemModel();

			String id_quotation = request.getParameter("id_quotation");
			if (id_quotation != null && !id_quotation.isEmpty()) {
				obj.setIdQuotation(Integer.parseInt(id_quotation));
			}

			String id_parent = request.getParameter("id_parent");
			if (id_parent != null && !id_parent.isEmpty()) {
				obj.setIdParent(Integer.parseInt(id_parent));
			}

			String code = request.getParameter("code");
			obj.setCode(code);

			String name = request.getParameter("name");
			obj.setName(name);

			String description = request.getParameter("description");
			obj.setDescription(description);

			String remark = request.getParameter("remark");
			obj.setRemark(remark);

			// P.V.Van modified 20/07/2011
			String is_group = request.getParameter("is_group");
			obj.setIsGroup(is_group != null);// is_group.equalsIgnoreCase("checked")
			// || is_group.equalsIgnoreCase("1"));

			// String in_estimate = request.getParameter("in_estimate");
			obj.setInEstimate(!obj.getIsGroup());// && in_estimate != null);//
			// in_estimate.equalsIgnoreCase("checked")
			// || in_estimate.equalsIgnoreCase("1"));

			String in_quotation = request.getParameter("in_quotation");
			obj.setInQuotation(!obj.getIsGroup() && in_quotation != null);
			// obj.setInQuotation(in_quotation.equalsIgnoreCase("checked")
			// || in_quotation.equalsIgnoreCase("1"));

			// String in_internal = request.getParameter("in_internal");
			obj.setInInternal(!obj.getIsGroup());// && in_internal != null);//
			// in_internal.equalsIgnoreCase("checked")
			// || in_internal.equalsIgnoreCase("1"));

			String index = request.getParameter("index");
			if (index != null && !index.isEmpty()) {
				obj.setIndex(Integer.parseInt(index));
			}

			String display_index = request.getParameter("display_index");
			obj.setDisplayIndex(display_index);

			// String id_product = request.getParameter("id_product");
			// if (id_product != null && !id_product.isEmpty()) {
			// obj.setIdProduct(Integer.parseInt(id_product));
			// }
			//
			// String id_service = request.getParameter("id_service");
			// if (id_service != null && !id_service.isEmpty()) {
			// obj.setIdService(Integer.parseInt(id_service));
			// }

			String id_unit = request.getParameter("id_unit");
			if (id_unit != null && !id_unit.isEmpty()) {
				obj.setIdUnit(Integer.parseInt(id_unit));
			}

			// String id_currency = request.getParameter("id_currency");
			// if (id_currency != null && !id_currency.isEmpty()) {
			// obj.setIdCurrency(Integer.parseInt(id_currency));
			// }

			String estimate_quantity = request.getParameter("estimate_quantity");
			if (obj.getInEstimate() && estimate_quantity != null && !estimate_quantity.isEmpty()) {
				obj.setEstimateQuantity(Integer.parseInt(estimate_quantity));
			}

			String estimate_unit_cost = request.getParameter("estimate_unit_cost");
			if (obj.getInEstimate() && estimate_unit_cost != null && !estimate_unit_cost.isEmpty()) {
				obj.setEstimateUnitCost(Double.parseDouble(estimate_unit_cost));
			}

			String estimate_total_amount = request.getParameter("estimate_total_amount");
			if (obj.getInEstimate() && estimate_total_amount != null && !estimate_total_amount.isEmpty()) {
				obj.setEstimateTotalAmount(Double.parseDouble(estimate_total_amount));
			}

			String internal_unit_cost = request.getParameter("internal_unit_cost");
			if (obj.getInInternal() && internal_unit_cost != null && !internal_unit_cost.isEmpty()) {
				obj.setInternalUnitCost(Double.parseDouble(internal_unit_cost));
			}

			String internal_quantity = request.getParameter("internal_quantity");
			if (obj.getInInternal() && internal_quantity != null && !internal_quantity.isEmpty()) {
				obj.setInternalQuantity(Integer.parseInt(internal_quantity));
			}

			String internal_total_amount = request.getParameter("internal_total_amount");
			if (obj.getInInternal() && internal_total_amount != null && !internal_total_amount.isEmpty()) {
				obj.setInternalTotalAmount(Double.parseDouble(internal_total_amount));
			}

			String quotation_unit_cost = request.getParameter("quotation_unit_cost");
			if (obj.getInQuotation() && quotation_unit_cost != null && !quotation_unit_cost.isEmpty()) {
				obj.setQuotationUnitCost(Double.parseDouble(quotation_unit_cost));
			}

			String quotation_quantity = request.getParameter("quotation_quantity");
			if (obj.getInQuotation() == true && quotation_quantity != null && !quotation_quantity.isEmpty()) {
				obj.setQuotationQuantity(Integer.parseInt(quotation_quantity));
			}

			String quotation_total_amount = request.getParameter("quotation_total_amount");
			if (obj.getInQuotation() && quotation_total_amount != null && !quotation_total_amount.isEmpty()) {
				obj.setQuotationTotalAmount(Double.parseDouble(quotation_total_amount));
			}
			// End of P.V.Van modified 20/07/2011

			String id_type = request.getParameter("id_type");
			if (id_type != null && !id_type.isEmpty()) {
				obj.setIdType(Integer.parseInt(id_type));
			}

			String status = request.getParameter("status");
			if (status != null && !status.isEmpty()) {
				obj.setStatus(Integer.parseInt(status));
			}

			String notification = request.getParameter("notification");
			if (notification != null && !notification.isEmpty()) {
				obj.setNotification(Integer.parseInt(notification));
			}

			obj.setCreator(SessionUtil.getCurrentUserID());

			if (CommonBll.checkInputs(obj)) {
				GenericDal<QuotationItemModel, QuotationItemModelExt> dal = new GenericDal<QuotationItemModel, QuotationItemModelExt>(new QuotationItemModel());

				int res = 0;
				try {
					res = dal.insert(obj);
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (ClassNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				if (res > 0) {
					// TODO : success, redirect to somewhere
					response.sendRedirect("quotation.jsp?id=" + obj.getIdQuotation());
				} else {
					// TODO : processing error here
				}
			} else {

				// invalid input

				request.setAttribute("quotation_item", obj);
				getServletContext().getRequestDispatcher("/quotationItemInput.jsp").forward(request, response);

			}
		} else if (mode.equalsIgnoreCase("update")) {

			QuotationItemModel query = new QuotationItemModel();
			String id = request.getParameter("id");
			query.setId(Integer.parseInt(id));

			GenericDal<QuotationItemModel, QuotationItemModelExt> dal = new GenericDal<QuotationItemModel, QuotationItemModelExt>(new QuotationItemModel());

			QuotationItemModel obj = null;
			try {
				obj = dal.select(query);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			if (obj != null) {

				String id_quotation = request.getParameter("id_quotation");
				if (id_quotation != null && !id_quotation.isEmpty()) {
					obj.setIdQuotation(Integer.parseInt(id_quotation));
				}

				String id_parent = request.getParameter("id_parent");
				if (id_parent != null && !id_parent.isEmpty()) {
					obj.setIdParent(Integer.parseInt(id_parent));
				}

				String code = request.getParameter("code");
				obj.setCode(code);

				String name = request.getParameter("name");
				obj.setName(name);

				String description = request.getParameter("description");
				obj.setDescription(description);

				String remark = request.getParameter("remark");
				obj.setRemark(remark);

				// P.V.Van modified [25/07/2011]
				String is_group = request.getParameter("is_group");
				obj.setIsGroup(is_group != null);
				obj.setIsGroupSet(true);

				String index = request.getParameter("index");
				obj.setIndex(index == null || index.isEmpty() ? Integer.MIN_VALUE : Integer.parseInt(index));

				String display_index = request.getParameter("display_index");
				obj.setDisplayIndex(display_index);

				String id_product = request.getParameter("id_product");
				obj.setIdProduct(id_product == null || id_product.isEmpty() ? Integer.MIN_VALUE : Integer.parseInt(id_product));

				String id_service = request.getParameter("id_service");
				obj.setIdService(id_service == null || id_service.isEmpty() ? Integer.MIN_VALUE : Integer.parseInt(id_service));

				String id_unit = request.getParameter("id_unit");
				obj.setIdUnit(id_unit == null || id_unit.isEmpty() ? Integer.MIN_VALUE : Integer.parseInt(id_unit));

				String id_currency = request.getParameter("id_currency");
				obj.setIdCurrency(id_service == null || id_service.isEmpty() ? Integer.MIN_VALUE : Integer.parseInt(id_currency));// P.V.Van
				// modified
				// [25/07/2011]

				// String in_estimate = request.getParameter("in_estimate");
				obj.setInEstimate(!obj.getIsGroup());

				String in_quotation = request.getParameter("in_quotation");
				obj.setInQuotation(!obj.getIsGroup() && in_quotation != null);

				// String in_internal = request.getParameter("in_internal");
				obj.setInInternal(!obj.getIsGroup());

				String estimate_quantity = request.getParameter("estimate_quantity");
				obj.setEstimateQuantity(!obj.getInEstimate() || estimate_quantity == null || estimate_quantity.isEmpty() ? Integer.MIN_VALUE : Integer.parseInt(estimate_quantity));

				String estimate_unit_cost = request.getParameter("estimate_unit_cost");
				obj.setEstimateUnitCost(!obj.getInEstimate() || estimate_unit_cost == null || estimate_unit_cost.isEmpty() ? Double.MIN_VALUE : Double.parseDouble(estimate_unit_cost));

				String estimate_total_amount = request.getParameter("estimate_total_amount");
				obj.setEstimateTotalAmount(!obj.getInEstimate() || estimate_total_amount == null || estimate_total_amount.isEmpty() ? Double.MIN_VALUE : Double.parseDouble(estimate_total_amount));

				String quotation_total_amount = request.getParameter("quotation_total_amount");
				obj.setQuotationTotalAmount(!obj.getInQuotation() || quotation_total_amount == null || quotation_total_amount.isEmpty() ? Double.MIN_VALUE : Double.parseDouble(quotation_total_amount));

				String quotation_unit_cost = request.getParameter("quotation_unit_cost");
				obj.setQuotationUnitCost(!obj.getInQuotation() || quotation_unit_cost == null || quotation_unit_cost.isEmpty() ? Double.MIN_VALUE : Double.parseDouble(quotation_unit_cost));

				String quotation_quantity = request.getParameter("quotation_quantity");
				obj.setQuotationQuantity(!obj.getInQuotation() || quotation_quantity == null || quotation_quantity.isEmpty() ? Integer.MIN_VALUE : Integer.parseInt(quotation_quantity));

				String internal_quantity = request.getParameter("internal_quantity");
				obj.setInternalQuantity(!obj.getInInternal() || internal_quantity == null || internal_quantity.isEmpty() ? Integer.MIN_VALUE : Integer.parseInt(internal_quantity));

				String internal_unit_cost = request.getParameter("internal_unit_cost");
				obj.setInternalUnitCost(!obj.getInInternal() || internal_unit_cost == null || internal_unit_cost.isEmpty() ? Double.MIN_VALUE : Double.parseDouble(internal_unit_cost));

				String internal_total_amount = request.getParameter("internal_total_amount");
				obj.setInternalTotalAmount(!obj.getInInternal() || internal_total_amount == null || internal_total_amount.isEmpty() ? Double.MIN_VALUE : Double.parseDouble(internal_total_amount));

				String id_type = request.getParameter("id_type");
				obj.setIdType(id_type == null || id_type.isEmpty() ? Integer.MIN_VALUE : Integer.parseInt(id_type));

				String status = request.getParameter("status");
				obj.setStatus(status == null || status.isEmpty() ? Integer.MIN_VALUE : Integer.parseInt(status));

				String notification = request.getParameter("notification");
				obj.setNotification(notification == null || notification.isEmpty() ? Integer.MIN_VALUE : Integer.parseInt(notification));
				// End of P.V.Van modifying.

				if (CommonBll.checkInputs(obj)) {

					int res = Integer.MIN_VALUE;
					try {
						res = dal.update(obj);
					} catch (SQLException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (ClassNotFoundException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

					if (res == 0) {
						// TODO success
						response.sendRedirect("quotation.jsp?id=" + obj.getIdQuotation());
					} else {
						// TODO error
					}
				} else {
					request.setAttribute("quotation_item", obj);
					getServletContext().getRequestDispatcher("/quotationItemEdit.jsp").forward(request, response);
				}
			} else {
				// TODO data not found
			}
		}
	}

}